import Axios from 'axios'
import { message } from 'ant-design-vue'
import { getToken, removeToken } from './auth'
import { throttledMsg } from './throttle'
import { refreshToken } from '@/utils/refreshToken'
import { store } from '@/store'
const baseURL = process.env.VUE_APP_BASE_URL // lyp开启共用地址
const axios = Axios.create({
  baseURL,
  timeout: 40000,
})
// 允许携带cookie
axios.defaults.withCredentials = false
// 请求头信息
axios.defaults.headers['X-Requested-With'] = 'XMLHttpRequest'
// 默认使用 application/json 形式
axios.defaults.headers.post['Content-Type'] = 'application/json'
// 请求拦截器
axios.interceptors.request.use(
  (res) => {
    const token = getToken()
    if (token) {
      // Authorization 改为 token 才能获取到数据
      res.headers['token'] = `${token}`
    }
    return res
  },
  (err) => Promise.reject(err),
)
// 响应拦截器
axios.interceptors.response.use(
  (res) => {
    if (res.data.code == '20003') {
      refreshToken()
        .then(async (result) => {
          if (result) {
            res.config.headers.token = result
            res = await axios.request(res.config)
            store.commit('user/SET_ISRELOAD', false)
          }
        })
        .catch((err) => {
          store.dispatch('user/logout').then(() => {
            window.location.href = '/login'
          })
        })
    } else {
      if (res.data.code == '22222') return
      return res
    }
  },
  (err) => {
    if (err.response && err.response.data) {
      const code = err.response.status
      const msg = err.response.statusText
      if (code === 409 || code === 1001 || err.response.data.code) {
        message.error(msg)
        return err.response
      } else if (code === 500) {
        throttledMsg(message.error('服务器错误'))
      } else if (code == 502) {
        throttledMsg(message.error('网关错误'))
      } else {
        throttledMsg(message.error(msg))
      }
    } else if (err.response?.status == 401) {
      throttledMsg(message.error('无权限, 请重新登录'))
      removeToken()
      window.location.reload()
      //Code: ${code}, Message:
    }
    // return Promise.reject({})
    return err
  },
)

export default axios.request
